

// 防止xss攻击，sql注入
const xss = require('xss')
exports.sqlfilter = function (obj, handle) {
  let newObj = obj instanceof Array ? [] : {}
  for (let key in obj) {
    let val = obj[key]
    if (typeof val === 'object') {
      newObj[key] = exports.sqlfilter(val, handle)
    } else {
      newObj[key] = handle(xss(val))
    }
  }
  return newObj
}

// 获取ip地址
exports.getIp = function (req) {
  let ip =
    req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.ip ||
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress ||
    ''
  if (ip) {
    ip = ip.replace('::ffff:', '')
  }
  return ip
}

// 解析ip地址获取地区信息
const searcher = require('node-ip2region').create()
exports.explainIp = function (ip) {
  return searcher.btreeSearchSync(ip)
}

// 解析user-agent获取设备信息等
const parser = require('ua-parser-js')
const sliceVersion = (version, count = 2) => {
  if (!version) return ''
  return version.split('.').slice(0, count).join('.')
}
exports.parserUa = function (ua) {
  const { browser = {}, os = {}, engine = {}, device = {} } = parser(ua)
  return {
    browser: browser.name
      ? `${browser.name}(${sliceVersion(browser.version)})`
      : '',
    device: device.vendor ? `${device.vendor} - ${device.model || ''}` : '',
    os: os.name ? `${os.name} - ${os.version || ''}` : '',
    engine: engine.name
      ? `${engine.name}(${sliceVersion(engine.version)})`
      : '',
    brand: device.vendor || '',
  }
}

// 获取随机x位sn
exports.getSn = function (x) {
  let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let sn = ''
  let num = 0
  for (let i = 0; i < x; i++) {
    num = parseInt(Math.floor(Math.random() * str.length))
    sn += str[num]
  }
  return sn
}

// 获取随机x位卡密
exports.getKey = function (x) {
  let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let sn = ''
  let num = 0
  for (let i = 0; i < x; i++) {
    num = parseInt(Math.floor(Math.random() * str.length))
    sn += str[num]
  }
  return sn
}

// 获取当前日期时间
exports.getToday = function () {
  var d = new Date()
  var hh = d.getHours()
  hh = hh.toString().padStart(2, '0')
  var mm = d.getMinutes()
  mm = mm.toString().padStart(2, '0')
  var ss = d.getSeconds()
  ss = ss.toString().padStart(2, '0')
  var day = d.getDate()
  day = day.toString().padStart(2, '0')
  var month = d.getMonth() + 1
  month = month.toString().padStart(2, '0')
  var year = d.getFullYear()
  return `${year}-${month}-${day} ${hh}:${mm}:${ss}`
}

// 获取今天日期
exports.getTodayDay = function () {
  var d = new Date() //昨天
  var day = d.getDate()
  day = day.toString().padStart(2, '0')
  var month = d.getMonth() + 1
  month = month.toString().padStart(2, '0')
  var year = d.getFullYear()
  return `${year}-${month}-${day}`
}

// 获取昨天日期
exports.getYesterdayDay = function () {
  var yesterday = new Date(new Date().setDate(new Date().getDate() - 1)) //昨天
  var day = yesterday.getDate()
  day = day.toString().padStart(2, '0')
  var month = yesterday.getMonth() + 1
  month = month.toString().padStart(2, '0')
  var year = yesterday.getFullYear()
  return `${year}-${month}-${day}`
}

// 获取设定日期
exports.getsetDay = function (time, num) {
  var d = new Date(new Date(time).setDate(new Date(time).getDate() + num)) //昨天
  var day = d.getDate()
  day = day.toString().padStart(2, '0')
  var month = d.getMonth() + 1
  month = month.toString().padStart(2, '0')
  var year = d.getFullYear()
  var hh = d.getHours()
  hh = hh.toString().padStart(2, '0')
  var mm = d.getMinutes()
  mm = mm.toString().padStart(2, '0')
  var ss = d.getSeconds()
  ss = ss.toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hh}:${mm}:${ss}`
}

// 获取下个月的今天日期
exports.nextMonthDay = function () {
  var yesterday = new Date(new Date().setDate(new Date().getDate() + 30)) //昨天
  var day = yesterday.getDate()
  day = day.toString().padStart(2, '0')
  var month = yesterday.getMonth() + 1
  month = month.toString().padStart(2, '0')
  var year = yesterday.getFullYear()
  return `${year}-${month}-${day}`
}

// 获取当前月所有日期
exports.getMonthDays = function () {
  var month = new Date().getMonth() + 1
  month = month.toString().padStart(2, '0')
  var year = new Date().getFullYear()
  var day = new Date(year, month, 0).getDate()
  let arr = []
  for (let i = 0; i < day; i++) {
    let day = (i + 1).toString().padStart(2, '0')
    arr.push(`${year}-${month}-${day}`)
  }
  return arr
}

// 获取本周所有日期
exports.getWeekDays = function () {
  const dateOfToday = Date.now()
  const dayOfToday = (new Date().getDay() + 7 - 1) % 7
  const daysOfThisWeek = Array.from(new Array(7)).map((_, i) => {
    const date = new Date(dateOfToday + (i - dayOfToday) * 1000 * 60 * 60 * 24)
    return (
      date.getFullYear() +
      '-' +
      String(date.getMonth() + 1).padStart(2, '0') +
      '-' +
      String(date.getDate()).padStart(2, '0')
    )
  })
  return daysOfThisWeek
}

exports.getClientIP = function (req) {
  let ip =
    req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.ip ||
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress ||
    ''
  if (ip) {
    ip = ip.replace('::ffff:', '')
  }
  return ip
}
